package com.bulletelc.apollopre.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.ListView;

import com.bulletelc.apollopre.R;

/**
 * Created by CX on 2018/4/4.
 */

public class ContainerHeightListView extends ListView{
    private float maxHeight = 720;
    public ContainerHeightListView(Context context) {
        super(context);
    }

    public ContainerHeightListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ContainerHeightListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ContainerHeightListView, 0, defStyleAttr);
        int count = typedArray.getIndexCount();
        for (int i=0; i< typedArray.length(); i++) {
            int type = typedArray.getIndex(i);
            if (type == R.styleable.ContainerHeightListView_maxHeight) {
                //获取限制最大高度
                maxHeight = typedArray.getDimension(type, -1);
            }
        }
        typedArray.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int specSize = MeasureSpec.getSize(heightMeasureSpec);  //获取ListView高度
        //限制高度小于lv高度，设置为限制高度
        if (maxHeight < specSize && maxHeight > -1) {
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(Float.valueOf(maxHeight).intValue(), MeasureSpec.AT_MOST);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
